<template>
  <div class="chat-page">
    <div class="chat-container">
      <div class="chat-header">
        <h2>DeepSeek Chat</h2>
        <p>AI-powered conversations</p>
      </div>
      <div class="chat-messages" ref="messagesContainer">
        <div v-for="(message, index) in messages" :key="index" :class="['message', message.sender]">
          <div class="message-content">{{ message.text }}</div>
        </div>
        <div v-if="isTyping" class="message deepseek">
          <div class="message-content typing">
            <span class="dot"></span>
            <span class="dot"></span>
            <span class="dot"></span>
          </div>
        </div>
      </div>
      <div class="chat-input">
        <input 
          v-model="userInput" 
          @keyup.enter="sendMessage" 
          placeholder="Type a message..." 
          :disabled="isTyping"
        />
        <button @click="sendMessage" :disabled="isTyping">
          <span>Send</span>
          <i class="fas fa-paper-plane"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userInput: '',
      messages: [],
      isTyping: false,
      currentResponse: ''
    };
  },
  methods: {
    async sendMessage() {
      if (this.userInput.trim() === '' || this.isTyping) return;

      // 添加用户消息
      this.messages.push({ text: this.userInput, sender: 'user' });
      const userMessage = this.userInput;
      this.userInput = '';
      this.isTyping = true;

      try {
        // 创建一个新的消息对象用于流式响应
        this.messages.push({ 
          text: '', 
          sender: 'deepseek',
          rawResponses: [] // 存储原始响应
        });
        const messageIndex = this.messages.length - 1;

        // 发送请求到后端
        const response = await fetch('http://106.227.89.45:899/common/ai/chat/stream', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            message: userMessage
          })
        });

        const reader = response.body.getReader();
        const decoder = new TextDecoder();

        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          
          const chunk = decoder.decode(value);
          const lines = chunk.split('\n');
          
          for (const line of lines) {
            if (line.trim() && line.trim().startsWith('data:')) {
              try {
                const data = line.substring(5).trim();
                if (data === '[DONE]') continue;
                
                const jsonData = JSON.parse(data);
                if (jsonData.choices && jsonData.choices[0].delta) {
                  const delta = jsonData.choices[0].delta;
                  
                  // 处理角色信息
                  if (delta.role) {
                    this.messages[messageIndex].role = delta.role;
                  }
                  
                  // 处理内容
                  if (delta.content) {
                    this.messages[messageIndex].text += delta.content;
                    // 强制更新视图
                    this.$forceUpdate();
                  }
                }
              } catch (e) {
                console.error('Error parsing JSON:', e);
              }
            }
          }
          
          // 滚动到最新消息
          this.$nextTick(() => {
            const messagesContainer = this.$refs.messagesContainer;
            if (messagesContainer) {
              messagesContainer.scrollTop = messagesContainer.scrollHeight;
            }
          });
        }
      } catch (error) {
        console.error('Error:', error);
        this.messages.push({
          text: '抱歉，处理您的请求时出现错误。',
          sender: 'deepseek'
        });
      } finally {
        this.isTyping = false;
      }
    }
  }
};
</script>

<style>
/* 引入Font Awesome */
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');

/* 全局样式 */
body, html {
  margin: 0;
  padding: 0;
  height: 100vh;
  width: 100vw;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: white;
  overflow: hidden; /* 防止body出现滚动条 */
}

/* 整个页面容器 */
.chat-page {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  background: white;
  overflow: hidden;
}

/* 聊天容器 */
.chat-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background: white;
}

/* 聊天头部 */
.chat-header {
  background: linear-gradient(135deg, #6a11cb, #2575fc);
  color: white;
  padding: 0;
  text-align: center;
  flex-shrink: 0;
  position: relative;
  z-index: 10;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 160px;
}

.chat-header h2 {
  margin: 0;
  padding: 0;
  font-size: 36px;
  font-weight: 600;
  line-height: 1.2;
}

.chat-header p {
  margin: 10px 0 0;
  padding: 0;
  font-size: 18px;
  opacity: 0.9;
  line-height: 1.4;
}

/* 聊天消息区域 */
.chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background: #f9f9f9;
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 0;
}

/* 自定义滚动条 */
.chat-messages::-webkit-scrollbar {
  width: 8px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #6a11cb;
  border-radius: 4px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

/* 消息样式 */
.message {
  display: flex;
}

.message-content {
  padding: 10px 15px;
  border-radius: 10px;
  max-width: 70%;
  word-wrap: break-word;
  animation: fadeIn 0.3s ease-in-out;
}

.user .message-content {
  background: #6a11cb;
  color: white;
  margin-left: auto;
  border-bottom-right-radius: 5px;
}

.deepseek .message-content {
  background: #e0e0e0;
  color: #333;
  margin-right: auto;
  border-bottom-left-radius: 5px;
}

/* 输入区域 */
.chat-input {
  display: flex;
  padding: 10px 15px;
  background: #fff;
  border-top: 1px solid #eee;
  gap: 10px;
  flex-shrink: 0;
}

.chat-input input {
  flex: 1;
  height: 44px;
  padding: 0 15px;
  border: 2px solid #ddd;
  border-radius: 10px;
  font-size: 14px;
  outline: none;
  transition: all 0.3s ease;
}

.chat-input button {
  height: 44px;
  padding: 0 20px;
  background: linear-gradient(135deg, #6a11cb, #2575fc);
  color: white;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.chat-input button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(106, 17, 203, 0.3);
}

.chat-input button i {
  margin-left: 5px;
}

/* 动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 添加打字动画样式 */
.typing {
  display: flex;
  align-items: center;
  min-width: 60px;
}

.dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  margin: 0 4px;
  background: #6a11cb;
  border-radius: 50%;
  animation: dot-flashing 1s infinite linear alternate;
}

.dot:nth-child(2) {
  animation-delay: 0.2s;
}

.dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes dot-flashing {
  0% {
    opacity: 0.2;
  }
  100% {
    opacity: 1;
  }
}

/* 禁用状态样式 */
.chat-input input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.chat-input button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none !important;
  box-shadow: none !important;
}
</style>